var tagInput = null;
var tagList = null;
var editor =null;

function init(){
	tagList = $('tag-list');
	tagInput = $('type-tag');
	//tag
	tagInput.addEvent('click',function(){ this.select(); });
	$('addTagBtn').addEvent('click',function(){
		tagInput.getProperty('value').trim().split(',').each(function(tag){
			addTag(tag);
		});
	});
	//栏目和选中效果
	$('pk_category_inner').getElements('input').addEvent('click',function(){
		var label=this.getNext('label');
        if(this.getProperty('checked')){
            label.setStyle('background-color','#80DCF0');
            addCheckedCategory(this);
        }else{
            label.setStyle('background-color','transparent');
            $('for-'+this.getProperty('id')).destroy();
        }
	});
	//编辑时用
    if(typeof edit_page != 'undefined'){
        if($type(edit_categoryies) == 'array'){
            edit_categoryies.each(function(item){
                $("cat"+item.many).click();
            });
        }
        if($type(edit_tags) == 'array'){
            edit_tags.each(function(item){
                addTag(item.name,item.id);
            });
        }
    }
}

$(window).addEvent('domready',function(){
    if(Browser.Engine.trident){
        window.setTimeout(function(){
            var size = $('pk_category_inner').getCoordinates();
            if(size.height>120){   //ie6~ie don't support max-height
                $('pk_category_inner').setStyle('height','120');
            }
            init();
        },500);
    }else{
        init();
    }
});

/**
 * 将选中的栏目显示于选中区
 */
function addCheckedCategory(inputObj){
    var fullName = inputObj.retrieve('fullName');
    if(!fullName){
        var stop = false;
        var div = inputObj.getParent();
        var names = [],lastply = 9999999;
        while(!stop){
            var ply = div.retrieve('ply');
            if(!ply){
                ply = parseInt(div.getStyle('padding-left'));
                if(ply>0) ply/=24;
                div.store('ply',ply);
            }
            if(ply < lastply){
                names.push(div.get('text'));
                lastply = ply;
            }
            if(ply == 0){
                stop = true;
            }else{
                div = div.getPrevious();
            }
        }
        names = names.reverse();
        fullName = names.join(' › ');
        inputObj.store('fullName',fullName);
    }
    var obj = new Element('li');
    obj.setProperty('id','for-'+inputObj.getProperty('id'));
    obj.grab(new Element('span',{text:fullName,events:{
        'click':function(){
            inputObj.focus();
        }
    }}));
    obj.grab(new Element('a',{
        html:'&nbsp;',
        events:{
            'click':function(){
                inputObj.click();
            }
        }
    }));
    $('pk_checked_category').grab(obj);
}

function addTag(tag,tagid){
    var li = new Element('li');
    var span = new Element('span',{html:tag});
    if(tagid) span.store('tagid',tagid);
    li.grab(span); 
    li.grab(new Element('a',{
        'href':'#nogo',
        'html':'&nbsp;',
        'events':{
            'click':function(){
                this.getParent().destroy();
            }
        }
    }));
    tagList.grab(li);
}

//保存草稿
function draft(){
	save('draft');
}
//表单动作
function save(status){
	var fm = preparedata();
	if(false === fm) return;
	fm.set('send',{
		url:fm.getAttribute('action'),
		method:'post',
		onSuccess:function(txt){
			var json = JSON.decode(txt);
            if(fm.elements['a'] == 'save'){
                fm.elements['id'].value = json.id;
                fm.elements['a'].value = 'update';
                //保存草稿按钮去掉
                $$('.fnc li:last-child').destroy();
            }
			var msg=(json.status) ? (json.data.msg || top.Lang['js_base_operate_success']) : ( json.info || top.Lang['js_base_operate_fail']);
			top.showMsg(msg,{type:json.status,disappear:1,onDisappear:function(){
                top.fixedMsg(json.status,msg);
            }});
		},
		onRequest:function(){
			top.showMsg(top.Lang['js_ajax_saveing']);
		}
	});
	fm.send();
}

//准备数据
function preparedata(){
	var fm = $(document.forms['mainForm']);
	//表单检查
	if(fm.elements['title'].value.trim()==''){
		//TODO
	}
	//准备tag信息
	var tags = [];
	tagList.getElements('span').each(function(span){
        var str = '{"name":"'+span.innerHTML+'"';       //暂时不考虑tag中包含单引号的影响
        var tagid = span.retrieve('tagid');
        if(tagid){ str+=',"id":"'+tagid+'"'; }
		tags.push(str+"}");
	});
	$('tag-list-hidden').setProperty('value',"["+tags.join(',')+"]");
	//准备meta信息--循环meta输入框，为其赋name值。meta的过滤放在服务器上做
	$$('#metas div').each(function(div,index){
		var metaKey = div.getFirst(),prefix = "meta["+index+"]";
		metaKey.setProperty('name',prefix+"[key]");
		metaKey.getNext().setProperty('name',prefix+"[value]");
	});
	//设置content值(mootools-ajax下使用)
	fm.elements['content'].value = editor.getData();
	return fm;
}



//从已有标签中选择标签
function selectTag(){
	
}
function addComma(aimInputId){
	var ips = $(aimInputId);
	ips.setProperty('value',ips.getProperty('value').trim()+',');
	ips.focus();
}

//缩略图
function toggleThumb(obj){
	$(obj).getParent().getNext().setStyle('display',obj.checked ? 'none':'block');
}

//删除元信息
function deleteMeta(btnObj){
	$(btnObj).getParent().destroy();
}
function addMeta(){
	var metaDiv = $('metas');
	var div = new Element('div');
	var ips_key = new Element('input',{'type':'text','class':'meta-key','size':'12'});
	var ips_value = new Element('input',{'type':'text','class':'meta-value','size':'36'});
	bindInputEff(ips_key);
	bindInputEff(ips_value);
	div.grab(ips_key);
	div.grab(ips_value);
	div.grab(new Element('button',{
		'class':'btn',
		'type':'button',
		'events':{
			'click':function(){ deleteMeta(this); }
		},
		'html':top.Lang['js_action_removal']
	}));
	metaDiv.grab(div);
}
//切换面板
function togglePanel(titleObj){
    var obj = $(titleObj);
	var contentObj = obj.getNext();
	var display = (contentObj.getStyle('display')=='none')?'block':'none';
	obj.setProperty('class',display=='block' ? 'panel-title' :'panel-title-collapse');
	contentObj.setStyle('display',display);		
}
//缩略图
var lastSetPic = null; //上一张选中的图片
function setThumb(){
    var gc=$("galleryContainer"),gallery=$("gallery");
    if(lastSetPic){
    	$("pk90").value=lastSetPic.src;
    }
    gc.style.display="none";
}
function getThumbFromContent(){
	var frame=$("cke_contents_editor").getElement("iframe");
    var editorDoc=frame.contentWindow.document;
    var imgs=editorDoc.getElementsByTagName("img"),imgslen=imgs.length;
    if(imgslen>0){
        var gc=$("galleryContainer"),gallery=$("gallery");
        gallery.empty();
        var currentThumbUrl = $('pk90').getProperty('value');
        for(var i=0;i<imgslen;i++){
            var oi=imgs[i];
            //创建图片并添加到其中去 
            var w=oi.width,h=oi.height;
            if(w>460){ h=460*h/w;w=460;}
            var img = new Element("img",{
            		'src':oi.src,'width':w,'height':h,
            		'styles':{'display':'block','margin':'0 auto','opacity':'0.4'},
            		'events':{
            			'mouseover':function(){ if(!this.retrieve('selected')) this.setStyle('opacity','0.8'); },
            			'mouseout':function(){ if(!this.retrieve('selected')) this.setStyle('opacity','0.4'); },
            			'click':function(){
            				if(lastSetPic){
            					lastSetPic.setStyles({'border-color':'#484848','opacity':'0.4'});
            					lastSetPic.store('selected',false);
            				}
            				this.setStyles({'border-color':'#6b7d1a','opacity':'1'});
            				this.store('selected',true);
            				lastSetPic = this;
            			}
            		}
            	});
            gallery.grab(img);
            if(currentThumbUrl == oi.src){
            	img.fireEvent('click');
            }
        }
        gallery.scrollTop=0;
        //定位并显示
        var win=$(window);
        var winsize=win.getSize();
        var scrollSize=win.getScroll();
        var winy=(winsize.y>420) ? winsize.y : 420;
        var winx=(winsize.x>480) ? winsize.x : 480;
        gc.setStyles({
            'top':(winy-380)/2+scrollSize.y+'px',
            'left':(winx-480)/2+'px',
            'display':'block'
        });
    }else{
        alert(top.Lang['gallery_no_pic']);
    }
}